package com.example.demo.test.service.impl;

import com.example.demo.test.dao.NewsMapper;
import com.example.demo.test.dao.NewsRepository;
import com.example.demo.test.entity.News;
import com.example.demo.test.service.NewsService;
import com.example.demo.test.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Service
@Component("NewsServiceImpl")
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsMapper newsMapper;
    @Resource
    private NewsRepository newsRepository;

    //一般方法
    @Override
    public void insertNews(News news) {
        newsMapper.save(news);
    }

    @Override
    @Transactional //事务管理
    public void deleteNews(int id) {
        newsMapper.deleteById(id);
    }

    @Override
    public void updateNews(News news) {
        newsMapper.save(news);
    }

    @Override
    public List<News> getNews() {
        return newsMapper.findAll();
    }

    @Override
    public News getNewsById(int id) {
        return newsMapper.findById(id);
    }





    //测试repository用
    @Override
    public Result saveNews(News news) {
        News save = newsRepository.save(news);
        return new Result(save);
    }

    @Override
    public Result queryAll() {
        List<News> list = newsRepository.findAll();
        return new Result(list);
    }

    /**
     * 分页查询实现
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result queryList(int page, int pageSize) {
        Pageable pageable = PageRequest.of(page,pageSize);
        List<News> list = newsRepository.findAll(pageable).getContent();
        return new Result(list);
    }

    /**
     * 结合实体类entity下@NamedQueries实现的查询
     * @param id
     * @return
     */
    @Override
    public Result findById(int id) {
        List<News> list = newsRepository.findById(id);
        return new Result(list);
    }

    /**
     * 使用@Query来指定本地查询
     * @param id
     * @return
     */
    @Override
    public Result findByIdWithQuery1(int id) {
        List<News> list = newsRepository.findByIdWithQuery1(id);
        return new Result(list);
    }

    @Override
    public Result findByIdWithQuery2(int id) {
        List<News> list = newsRepository.findByIdWithQuery2(id);
        return new Result(list);
    }


    @Override
    public Result getByTitle(String title) {
        List<News> list = newsRepository.getByTitle(title);
        return new Result(list);
    }
}
